<?php
/**
 * Model class link to table master_area in database
 *
 * @author Dat Nguyen <datn@evolable.asia>
 */
class Area extends AppModel {
	var $name = 'Area';
	var $useTable = 'area';
	var $tablePrefix = 'master_';
	var $primaryKey = 'id';
	var $order = 'rank asc';

	/**
	 * Get area that belong to course
	 *
	 * @param $course
	 * @return array
	 */
	function getByCourse ($course) {
		$options = array(
			'conditions' => array(),
			'recursive' => -1,
		);
		if (isset($course['Course']['area'])) {
			$options['conditions'] = array(
				'id' => $course['Course']['area'],
			);
		}

		return  $this->find('first', $options);
	}
	
	/**
	 * Get area by primary key
	 *
	 * @param $id
	 * @return array
	 */
	function getById ($id) {
		$options = array(
			'conditions' => array(),
			'recursive' => -1,
		);
		$options['conditions'] = array(
			'id' => $id,
		);


		return  $this->find('first', $options);
	}

	/**
	 * Get total courses in each area
	 * @return array
	 */
	function getCourseStatistic() {
		$options = array(
			'recursive' => -1,
			'fields' => array(
				$this->alias . '.*',
				'Course.total_course',
			),
			'joins' => array(
				array(
					'table' => '(SELECT c.area, COUNT(c.id) AS total_course FROM courses c WHERE c.del_flg = 0 GROUP BY area)',
					'alias' => 'Course',
					'type' => 'LEFT',
					'conditions' => array(
						$this->alias . '.id = Course.area'
					)
				),
			),
		);

		return $this->find('all', $options);
	}
}